package com.yxw.asyncload;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView mListView;
    private static String URI = "http://www.imooc.com/api/teacher?type=4&num=30";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView = findViewById(R.id.lv_main);
        //execute方法里要传如URI，不然会报错，导致app打不开
        new NewsAsyncTask().execute(URI);
    }

    /**
     * 将url对应的json格式数据转化为我们所封装的NewsBean
     * @param url
     * @return
     */
    private List<NewsBean> getJsonData(String url) {
        List<NewsBean> newsBeansList = new ArrayList<NewsBean>();
        try {
            String jsonString = readStream(new URL(url).openStream());
            JSONObject jsonObject;
            NewsBean newsBean;

            try {
                jsonObject = new JSONObject(jsonString);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < jsonArray.length(); i++) {
                    jsonObject = jsonArray.getJSONObject(i);
                    newsBean = new NewsBean();
                    newsBean.newsTtitle = jsonObject.getString("name");
                    newsBean.newsContent = jsonObject.getString("description");
                    newsBean.newsIconUrl = jsonObject.getString("picSmall");
                    newsBeansList.add(newsBean);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


        return newsBeansList;
    }

    /**
     * 通过is解析网页返回的数据
     * @param is
     * @return
     */
    private String readStream(InputStream is) {
        InputStreamReader isr;
        String result = "";
        try {
            String lines = "";
            isr = new InputStreamReader(is, "utf-8");//字节流转化为字符流
            BufferedReader br = new BufferedReader(isr);
            while((lines = br.readLine()) != null) {
                result += lines;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 实现网络的异步访问
     *第一个参数:String类型的请求网络组
     * 第二个参数:progress，我们不需要记录中间过程，所以传一个Void
     * 第二个参数：返回的result，我们需要把json格式进行封装，便于我们在adapter中设置数据
     */
    class NewsAsyncTask extends AsyncTask<String, Void, List<NewsBean>> {
        /**
         * 获取到传进来的url，json数据请求的网址，通过这样一个api，返回json格式数据，并构造一个
         * NewsBean的List
         * @param params
         * @return
         */
        @Override
        protected List<NewsBean> doInBackground(String... params) {
            /*
            这里出了个错误，说是数组越界
             */
            return getJsonData(params[0]);
        }

        @Override
        protected void onPostExecute(List<NewsBean> newsBeans) {
            super.onPostExecute(newsBeans);
            NewsAdapter newsAdapter= new NewsAdapter(MainActivity.this,newsBeans);
            mListView.setAdapter(newsAdapter);
        }
    }
}
